<?php
namespace app\controllers\api\comment;

use fate\http\Request;
use app\models\UserCredit;
use app\models\UserCreditLog;
use app\models\CommentCenter;
use app\libs\LibUser;
use app\libs\Sys;
use app\libs\Util;

class AddController extends \fate\web\PureController {

    public function run() {
        global $_G;
        $req = Request::getInstance();

        // 是否登录
        $uid = LibUser::getLoginUid();
        if('' === $uid) {
            $this->ajaxReturn(null, 200001, 'not login');
            exit;
        }

        $ip = Util::plainText($req->getUserIP());
        $projectId = $req->getParameter('project_id');
        $postId = $req->getParameter('post_id');
        $parentId = $req->getParameter('parent_id');
        $agent = Util::plainText($req->getParameter('user_agent'));
        $content = Util::plainText($req->getParameter('data'));

        if(!is_numeric($projectId)) {
            $this->ajaxReturn(null, 300002, 'project id error');
            exit;
        }
        if(!is_numeric($postId)) {
            $this->ajaxReturn(null, 300002, 'id error');
            exit;
        }
        if(!is_numeric($parentId)) {
            $this->ajaxReturn(null, 300002, 'parent id error');
            exit;
        }
        // 检查数据
        if(!$content || Util::strlenOfCN($content) > 200) {
            $this->ajaxReturn(null, 300002, 'content too long');
            exit;
        }

        // 数据
        $data = [
            'project_id' => $projectId,
            'project_inner_id' => $postId,
            'parent_id' => $parentId,
            'uid' => $uid,
            'post_time' => $_G['now_time'],
            'ip' => $ip,
            'user_agent' => $agent,
            'content' => $content
        ];

        $cc = new CommentCenter();

        // 检查 ip 一天 50 条
        // $time = $_G['now_time'] - 24 * 60 * 60;
        // $ret = $cc->count('ip=\'' . $ip . '\' AND post_time > ' . $time);
        // if($ret > 50) {
        //     $this->ajaxReturn(null, 300001);
        //     exit;
        // }

        $cc->insert($data);

        $exp = Sys::getCommentExp();
        if($exp > 0) {
            (new UserCredit())->addExp($uid, $exp);

            // log
            $log = [
                'uid' => $uid,
                'experience' => $exp,
                'action' => UserCreditLog::$ACTION_POST_COMMENT,
                'log_time' => $_G['now_time']
            ];
            (new UserCreditLog())->insert($log);
        }

        $this->ajaxReturn(null);
    }

}
